﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExaminationSys.DataAccess;
using ExaminationSys.DataAccess.Entity;
using ExaminationSys.DataAccess.Repository;
using ExaminationSys.Helper;
using Ext.Net;
using System.IO;

namespace ExaminationSys.View.SystemManage
{
    public partial class DBQuestionEdit : System.Web.UI.UserControl
    {
        private static readonly DBQuestionService Proxy = ObjectFactory<DBQuestionService>.Create();
        private static readonly DBAnswerService ProxyDBAnswer = ObjectFactory<DBAnswerService>.Create();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                Bind();
            }
        }
        private void Bind()
        {
            // TO DO
        }

        public Store GridStore { get; set; }
        public string ID { get; set; }


        public void SetData(string id)
        {
            KeyWord.Text = "";
            Knowledge.Text = "";
            QuestionType.Text = "";
            SubjectType.Text = "";
            Challenge.Text = "";
            Point.Text = "0";
            Stage.Text = "";
            AttachFile.Text = "";
            Content.Text = "";
            txtA.Text = "";
            txtB.Text = "";
            txtC.Text = "";
            txtD.Text = "";
            txtE.Text = "";
            chkA.Checked = false;
            chkB.Checked = false;
            chkC.Checked = false;
            chkD.Checked = false;
            chkE.Checked = false;
            txtA.Tag = "";
            txtB.Tag = "";
            txtC.Tag = "";
            txtD.Tag = "";
            txtE.Tag = "";
            txtSerialNo.Value = "";
            txtIDA.Text = "";
            txtIDB.Text = "";
            txtIDC.Text = "";
            txtIDD.Text = "";
            txtIDE.Text = "";
            txtAttachFile.Value = "";
            this.DBQuestionEditWindow.Title = "题库管理(普通题)新增";
            QuestionType.Select(0);
            Challenge.Select(2);
            Point.Number = 1;
            Stage.Select(2);
            SubjectType.Select(0);
            if (!string.IsNullOrEmpty(id))
            {
                this.DBQuestionEditWindow.Title = "题库管理(普通题)修改";
                var realId = new Guid(id);
                var dbquestion = Proxy.Get(realId);

                KeyWord.Text = dbquestion.KeyWord;
                Knowledge.Text = dbquestion.Knowledge;
                QuestionType.Text = dbquestion.QuestionType;
                SubjectType.Text = dbquestion.SubjectType;
                Challenge.Text = dbquestion.Challenge;
                Point.Text = dbquestion.Point.ToString();
                Stage.Text = dbquestion.Stage;
                AttachFile.Text = dbquestion.AttachFile;
                Content.Text = dbquestion.Content;
                //txtAttachFile.Value = dbquestion.AttachFile;
                //txtSerialNo.Value = dbquestion.SerialNo;
                X.Js.Call("attachFile", dbquestion.AttachFile);
                X.Js.Call("serialNo", dbquestion.SerialNo);
                hidSerialNo.Value = dbquestion.SerialNo;

                List<DBAnswer> list = ProxyDBAnswer.GetAll(dbquestion.ID);
                Window w = this.DBQuestionEditWindow;
                string prefix = string.Empty;
                foreach (DBAnswer dbanswer in list)
                {
                    prefix = dbanswer.Prefix.Trim();
                    TextField txt = w.FindControl("txt" + prefix) as TextField;
                    Checkbox chk = w.FindControl("chk" + prefix) as Checkbox;
                    TextField txtid = w.FindControl("txtID" + prefix) as TextField;

                    txt.Text = dbanswer.Content;
                    txtid.Text = dbanswer.ID.ToString();
                    chk.Checked = dbanswer.IsRight;

                    prefix = string.Empty;
                }
                LockHidden.Value = dbquestion.Lock.ToString();
                chkLock.Checked = dbquestion.Lock;
                X.Js.Call("lock", dbquestion.Lock);

                ID = id;
                X.Js.Call("setID", id);
            }
        }

        public void Show()
        {
            this.DBQuestionEditWindow.Show();
        }

        protected void SaveDBQuestion(object sender, DirectEventArgs e)
        {
            List<string> listPrefix = new List<string>();
            listPrefix.Add("A");
            listPrefix.Add("B");
            listPrefix.Add("C");
            listPrefix.Add("D");
            listPrefix.Add("E");

            var keyword = KeyWord.Text.Trim();
            var knowledge = Knowledge.Text.Trim();
            var questiontype = QuestionType.Text.Trim();// 请选择类型
            var subjecttype = SubjectType.Text.Trim(); // 题型
            var challenge = Challenge.Text.Trim(); // 难度
            var point = Point.Text.Trim();
            var stage = Stage.Text;
            var content = Content.Text.Trim();
            var attachfile = txtAttachFile.Value;
            bool questionexists = Proxy.CheckContent(content, "普通题");
            if (questionexists && string.IsNullOrEmpty(DBQuestionIDHidden.Value))
            {
                MessageBoxHelper.ShowWarning("该题已经存在");
                return;
            }

            // 答案
            bool flag = AnswerContentCheck(listPrefix);
            if (!flag)
                return;

            if (AttachFile.HasFile && subjecttype.Equals("视听"))
            {
                #region 附件上传
                attachfile = this.AttachFile.PostedFile.FileName.ToString();
                string strFileName = Path.GetExtension(this.AttachFile.PostedFile.FileName).ToUpper();
                //获取文件后缀              
                if (!(strFileName == ".MP3" || strFileName == ".MP4" || strFileName == ".AVI"))
                {
                    MessageBoxHelper.ShowWarning("文件格式不正确！\r\n只能上传MP3、MP4、AVI 文件");
                    return;
                }

                int FileSize = Int32.Parse(this.AttachFile.PostedFile.ContentLength.ToString());
                if (FileSize > 30 * 1024 * 1024)
                {
                    MessageBoxHelper.ShowWarning("上传文件过大");
                    return;
                }

                var fileNameTmp = Path.GetFileName(this.AttachFile.PostedFile.FileName);
                string fileName = string.Format("{0}_{1}_{2}", Guid.NewGuid().ToString(), DateTime.Now.ToString("yyyyMMddHHmm"), fileNameTmp);
                var filePath = string.Format("{0}/DBQuestion", UIHelpers.BasePath);
                string fileFullName = Path.Combine(Server.MapPath(filePath), fileName);

                try
                {
                    this.AttachFile.PostedFile.SaveAs(fileFullName);
                    attachfile = fileName;
                    txtAttachFile.Value = fileName;
                }
                catch (Exception ex)
                {
                    MessageBoxHelper.ShowError("附件上传出错", ex.Message);
                    return;
                }
                #endregion
            }
            else if (!subjecttype.Equals("视听"))
                attachfile = string.Empty;
            
            // 题目
            #region 条件
            //if (string.IsNullOrWhiteSpace(keyword))
            //{
            //    MessageBoxHelper.ShowWarning("关键字不能为空");
            //    return;
            //}
            //if (string.IsNullOrWhiteSpace(knowledge))
            //{
            //    MessageBoxHelper.ShowWarning("知识点不能为空");
            //    return;
            //}
            if (string.IsNullOrEmpty(questiontype))
            {
                MessageBoxHelper.ShowWarning("类型不能为空");
                return;
            }
            if (string.IsNullOrEmpty(subjecttype))
            {
                MessageBoxHelper.ShowWarning("题型不能为空");
                return;
            }
            if (string.IsNullOrEmpty(challenge))
            {
                MessageBoxHelper.ShowWarning("难度不能为空");
                return;
            }
            if (string.IsNullOrEmpty(point))
            {
                MessageBoxHelper.ShowWarning("分值不能为空");
                return;
            }
            if (string.IsNullOrEmpty(stage))
            {
                MessageBoxHelper.ShowWarning("阶段不能为空");
                return;
            }
            if (string.IsNullOrEmpty(content))
            {
                MessageBoxHelper.ShowWarning("内容题目不能为空");
                return;
            }
            if (subjecttype.Equals("视听") && string.IsNullOrEmpty(attachfile))
            {
                MessageBoxHelper.ShowWarning("视听题，视听附件不能为空");
                return;
            }
            #endregion

            var id = DBQuestionIDHidden.Value;
            var actionflag = string.IsNullOrWhiteSpace(id);
            Guid realId = string.IsNullOrEmpty(id) ? Guid.NewGuid() : new Guid(id);
            
            ExaminationSys.DataAccess.Entity.DBQuestion entity = new DataAccess.Entity.DBQuestion();
            string headstr = System.DateTime.Now.ToString("yyyyMMdd");
            entity.ID = realId;
            entity.SerialNo = string.IsNullOrEmpty(txtSerialNo.Value) ? Proxy.GetSerialNo(headstr) : txtSerialNo.Value;
            entity.KeyWord = keyword;
            entity.Knowledge = knowledge;
            entity.QuestionType = questiontype;
            entity.DBQuestionType = "普通题";
            entity.SubjectType = subjecttype;
            entity.Challenge = challenge;
            entity.Point = Decimal.Parse(point);
            entity.Stage = stage;
            entity.AttachFile = attachfile;
            entity.Content = content;

            entity.Title = "";
            entity.Status = 1;
            entity.AddTime = DateTime.Now;
            entity.Lock = chkLock.Checked;


            var op = FormsAuthenticationHelper.GetCurrentUserID();
            if (string.IsNullOrEmpty(op))
            {
                FormsAuthenticationHelper.SignOut();
                Response.Redirect("~/Account/Login.aspx");
            }
            entity.Operator = op;

            entity.OperatorTime = DateTime.Now;
            
            var sucess = false;

            //if (actionflag)
            //{
            //    var retCode = Proxy.Insert(entity);
            //    sucess = retCode != null;
            //    sucess = AnswerAddOrUpdate(sucess, realId, listPrefix, true);
            //}
            //else
            //{
            //    sucess = Proxy.Update(entity);
            //    sucess = AnswerAddOrUpdate(sucess, realId, listPrefix, false);
            //}
            List<DBAnswer> listdBAnswer = new List<DBAnswer>();
            listdBAnswer = AnswerAddOrUpdate3(entity, listPrefix);

            sucess = Proxy.AnswerAddOrUpdate(entity, listdBAnswer, actionflag, null);

            if (sucess)
            {
                //MessageBoxHelper.ShowInfo("保存成功");
                GridStore.Reload();
                DBQuestionEditWindow.Hide();
            }
            else
            {
                MessageBoxHelper.ShowInfo("保存失败");
                return;
            }            
        }
        /// <summary>
        /// 答案选项检查
        /// </summary>
        /// <returns></returns>
        private bool AnswerContentCheck(List<string> listPrfix)
        {
            var questiontype = QuestionType.Text.Trim();
            Window w = this.DBQuestionEditWindow;
            int all = 0, chkall = 0;
            foreach (string prefix in listPrfix)
            {
                TextField txt = w.FindControl("txt" + prefix) as TextField;
                Checkbox chk = w.FindControl("chk" + prefix) as Checkbox;
                if (string.IsNullOrEmpty(txt.Text.Trim()) && chk.Checked)
                {
                    MessageBoxHelper.ShowWarning("答案内容为空不能是正确答案");
                    return false;
                }
                if (!string.IsNullOrEmpty(txt.Text.Trim()))
                    all++;
                if (chk.Checked)
                    chkall++;
            }
            if (questiontype.Equals("单选"))
            {
                if (all < 2)
                {
                    MessageBoxHelper.ShowWarning("单选题：答案选项必须至少为两个");
                    return false;
                }
                else if (chkall != 1)
                {
                    MessageBoxHelper.ShowWarning("单选题：正确答案有且只有一个");
                    return false;
                }
            }
            else if (questiontype.Equals("多选"))
            {
                if (all < 3)
                {
                    MessageBoxHelper.ShowWarning("多选题：答案选项必须至少为三个");
                    return false;
                }
                else if (chkall < 2)
                {
                    MessageBoxHelper.ShowWarning("多选题：正确答案必须大于一个");
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 答案项更新
        /// </summary>
        private bool AnswerAddOrUpdate(bool sucess, Guid realId, List<string> listPrefix, bool addFlag)
        {
            if (sucess)
            {
                #region 答案-OLD
                /*
                DBAnswer dbanswer = new DBAnswer();
                dbanswer.Lock = false;
                dbanswer.Status = 1;
                dbanswer.OperatorTime = DateTime.Now;
                
                 * 
                var op = FormsAuthenticationHelper.GetCurrentUserID();
                if (string.IsNullOrEmpty(op))
                {
                    FormsAuthenticationHelper.SignOut();
                    Response.Redirect("~/Account/Login.aspx");
                }
                dbanswer.Operator = op;

                dbanswer.DBQuestionID = realId;
                if (string.IsNullOrEmpty(txtIDA.Text) && !string.IsNullOrEmpty(txtA.Text.Trim()))
                {
                    dbanswer.ID = Guid.NewGuid();
                    dbanswer.Prefix = "A";
                    dbanswer.Content = txtA.Text.Trim();
                    dbanswer.IsRight = chkA.Checked;
                    ProxyDBAnswer.Insert(dbanswer);
                }
                if (!string.IsNullOrEmpty(txtIDA.Text))
                {
                    dbanswer.ID = new Guid(txtIDA.Text);
                    if (string.IsNullOrEmpty(txtA.Text.Trim()))
                    {
                        List<string> list = new List<string>();
                        list.Add(dbanswer.ID.ToString());
                        ProxyDBAnswer.Delete(list);
                    }
                    else
                    {
                        dbanswer.Prefix = "A";
                        dbanswer.Content = txtA.Text.Trim();
                        dbanswer.IsRight = chkA.Checked;
                        ProxyDBAnswer.Update(dbanswer);
                    }
                }

                if (!string.IsNullOrEmpty(txtIDB.Text))
                {
                    dbanswer.ID = new Guid(txtIDB.Text);
                    dbanswer.Prefix = "B";
                    dbanswer.Content = txtB.Text.Trim();
                    dbanswer.IsRight = chkB.Checked;
                    ProxyDBAnswer.Update(dbanswer);
                }
                if (!string.IsNullOrEmpty(txtIDC.Text))
                {
                    dbanswer.ID = new Guid(txtIDC.Text);
                    dbanswer.Prefix = "C";
                    dbanswer.Content = txtC.Text.Trim();
                    dbanswer.IsRight = chkC.Checked;
                    ProxyDBAnswer.Update(dbanswer);
                }
                if (!string.IsNullOrEmpty(txtIDD.Text))
                {
                    dbanswer.ID = new Guid(txtIDD.Text);
                    dbanswer.Prefix = "D";
                    dbanswer.Content = txtD.Text.Trim();
                    dbanswer.IsRight = chkD.Checked;
                    ProxyDBAnswer.Update(dbanswer);
                }
                if (!string.IsNullOrEmpty(txtIDE.Text))
                {
                    dbanswer.ID = new Guid(txtIDE.Text);
                    dbanswer.Prefix = "E";
                    dbanswer.Content = txtE.Text.Trim();
                    dbanswer.IsRight = chkE.Checked;
                    ProxyDBAnswer.Update(dbanswer);
                }
                 */
                #endregion

                sucess = AnswerAddOrUpdate2(listPrefix, realId, addFlag);

                if (!sucess)
                {
                    List<string> list = new List<string>();
                    list.Add(realId.ToString());
                    Proxy.Delete(list);
                }
            }
            return sucess;
        }

        private bool AnswerAddOrUpdate2(List<string> listPrefix, Guid realId, bool addFlag)
        {
            if (listPrefix != null && listPrefix.Count > 0)
            {
                List<string> listDelete = new List<string>();
                try
                {
                    foreach (string prefix in listPrefix)
                    {
                        DBAnswer dbanswer = new DBAnswer();
                        dbanswer.Lock = false;
                        dbanswer.Status = 1;
                        dbanswer.OperatorTime = DateTime.Now;

                        var op = FormsAuthenticationHelper.GetCurrentUserID();
                        if (string.IsNullOrEmpty(op))
                        {
                            FormsAuthenticationHelper.SignOut();
                            Response.Redirect("~/Account/Login.aspx");
                        }
                        dbanswer.Operator = op;

                        dbanswer.DBQuestionID = realId;

                        Window w = this.DBQuestionEditWindow;

                        TextField txt = w.FindControl("txt" + prefix) as TextField;
                        Checkbox chk = w.FindControl("chk" + prefix) as Checkbox;
                        TextField txtid = w.FindControl("txtID" + prefix) as TextField;

                        if ((addFlag || string.IsNullOrEmpty(txtid.Text)) && !string.IsNullOrEmpty(txt.Text.Trim()))
                        {
                            dbanswer.ID = Guid.NewGuid();
                            dbanswer.Prefix = prefix;
                            dbanswer.Content = txt.Text.Trim();
                            dbanswer.IsRight = chk.Checked;
                            var retCode = ProxyDBAnswer.Insert(dbanswer);
                            if (retCode != null)
                                listDelete.Add(dbanswer.ID.ToString());
                        }
                        else if (!string.IsNullOrEmpty(txtid.Text))
                        {
                            dbanswer.ID = new Guid(txtid.Text);
                            if (string.IsNullOrEmpty(txt.Text.Trim()))
                            {
                                List<string> list = new List<string>();
                                list.Add(dbanswer.ID.ToString());
                                ProxyDBAnswer.Delete(list);
                            }
                            else
                            {
                                dbanswer.Prefix = prefix;
                                dbanswer.Content = txt.Text.Trim();
                                dbanswer.IsRight = chk.Checked;
                                ProxyDBAnswer.Update(dbanswer);
                            }
                        }
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    ProxyDBAnswer.Delete(listDelete);
                }
            }
            return false;
        }

        private List<DBAnswer> AnswerAddOrUpdate3(DBQuestion dBquestion, List<string> listPrefix)
        {
            List<DBAnswer> listdBAnswer = new List<DBAnswer>();
            try
            {
                Window w = this.DBQuestionEditWindow;

                foreach (string prefix in listPrefix)
                {
                    TextField txt = w.FindControl("txt" + prefix) as TextField;
                    Checkbox chk = w.FindControl("chk" + prefix) as Checkbox;
                    TextField txtid = w.FindControl("txtID" + prefix) as TextField;

                    if (!string.IsNullOrEmpty(txt.Text.Trim()))
                    {
                        DBAnswer dbanswer = new DBAnswer();
                        dbanswer.Lock = false;
                        dbanswer.Status = 1;
                        dbanswer.OperatorTime = DateTime.Now;
                        dbanswer.Operator = dBquestion.Operator;
                        dbanswer.DBQuestionID = dBquestion.ID;
                        dbanswer.ID = Guid.NewGuid();
                        dbanswer.Prefix = prefix;
                        dbanswer.Content = txt.Text.Trim();
                        dbanswer.IsRight = chk.Checked;
                        listdBAnswer.Add(dbanswer);
                    }
                }
            }
            catch (Exception ex)
            {
                listdBAnswer = new List<DBAnswer>();
            }

            return listdBAnswer;
        }
    }
}